package com.ak.jddemo.test;

import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author: ak
 * @date: 2021/4/20 9:43
 * @description:
 */
@Slf4j
public class SeckillService2 {
    //最大失败次数
    public static final int ERROR_TIMES = 50;
    public static List<String> COOKIE = null;
    static Map<String, List<String>> stringListMap = new HashMap<String, List<String>>();
    static AtomicInteger integer = new AtomicInteger();
    static JSONObject subData = new JSONObject();
    static String initReferer;


    @SneakyThrows
    public static void begin() {
        //提交订单
        ExecutorService service = Executors.newFixedThreadPool(8);
        Runnable task = getTask();
        while (Config.status == 0) {
            service.execute(task);
        }
        log.info("抢购结束");
    }

    private static Runnable getTask() {
        long start = System.currentTimeMillis();
        return new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                if (Config.status == 0) {
                    String result = HttpUrlConnectionUtil.doPost("https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action?skuId=" + Config.pid, subData, getSubmitHeader(),true);
                    log.info("下单耗时{}秒", (System.currentTimeMillis() - start) / 1000d);
                    try {
                        log.info("抢购结果: {}", result);
                        log.info("已抢购{}次", integer.incrementAndGet());
                        if (integer.get() > ERROR_TIMES) {
                            System.exit(0);
                        }
                    } catch (Exception e) {
                        log.error("抢购失败", e);
                    }
                }
            }
        };
    }

    public static JSONObject getOrderInfoHeader() throws IOException, URISyntaxException {
        JSONObject headers = new JSONObject();
        headers.put("Cookie", COOKIE.get(0));
        headers.put("sec-ch-ua-mobile", "?0");
        headers.put("sec-ch-ua", "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"90\", \"Microsoft Edge\";v=\"90\"");
        headers.put("sec-fetch-dest", "document");
        headers.put("sec-fetch-mode", "navigate");
        headers.put("sec-fetch-site", "none");
        headers.put("sec-fetch-user", "?1");
        headers.put("upgrade-insecure-requests", 1);
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36 Edg/90.0.818.42");
        return headers;
    }

    public static JSONObject getInitHeaders() {
        JSONObject initHeaders = new JSONObject();
        initHeaders.put("cookie", COOKIE.get(0));
        initHeaders.put(Config.headerAgent, Config.headerAgentArgWin);
        return initHeaders;
    }

    private static JSONObject getSubmitHeader() {
        return getInitHeaders();
    }

    public static void initSubData(JSONObject jsonObject) {
        log.info("初始化参数");
        JSONObject addressList = jsonObject.getJSONArray("addressList").getJSONObject(0);
        JSONObject invoiceInfo = jsonObject.getJSONObject("invoiceInfo");
        if (addressList.get("name") != null) {
            log.info("初始化参数成功");
        }
        subData.put("skuId", Config.pid);
        subData.put("num", 1);
        subData.put("addressId",addressList.get("id"));
        subData.put("yuShou", true);
        subData.put("isModifyAddress", "false");
        subData.put("name", addressList.get("name"));
        //provinceId
        subData.put("provinceId", addressList.get("provinceId"));
        subData.put("cityId", addressList.get("cityId"));
        subData.put("countyId", addressList.get("countyId"));
        subData.put("townId", addressList.get("townId"));
        subData.put("addressDetail", addressList.get("addressDetail"));
        subData.put("mobile", addressList.get("mobile"));
        subData.put("email: ", "");
        subData.put("postCode", addressList.get("postCode"));
        subData.put("invoiceTitle", invoiceInfo.get("invoiceTitle"));
        subData.put("invoiceCompanyName", invoiceInfo.get("invoiceCompany"));
        subData.put("invoiceContent", invoiceInfo.get("invoiceContentType"));
        subData.put("invoiceTaxpayerNO", "");
        subData.put("invoiceEmail: ", "");
        subData.put("invoicePhone", invoiceInfo.get("invoicePhone"));
        subData.put("invoicePhoneKey", invoiceInfo.get("invoicePhoneKey"));
        subData.put("invoice", true);
        subData.put("codTimeType", 3);
        subData.put("paymentType: ", 4);
        subData.put("areaCode", addressList.get("areaCode"));
        subData.put("overseas", addressList.get("overseas"));
        subData.put("phone","");
        subData.put("eid", Config.eid);
        subData.put("fp", Config.fp);
        subData.put("token", jsonObject.get("token"));
        subData.put("provinceName", addressList.get("provinceName"));
        subData.put("cityName", addressList.get("cityName"));
        subData.put("countyName", addressList.get("countyName"));
        subData.put("townName", addressList.get("townName"));
//        subData.put("sk","mYzWziLu74nhq5qyyqp");
        log.info("参数:{}", subData);
    }

    public static void preparation(JSONObject headers) throws IOException, URISyntaxException {
        String targetUrl = null;
        try {
            targetUrl = HttpUrlConnectionUtil.getTargetUrl(headers);
        } catch (ParseException | InterruptedException e) {
            e.printStackTrace();
        }
        log.info("抢购连接: {}", targetUrl);
        HttpUrlConnectionUtil.sendClearingUrl(headers, targetUrl);
    }

    public static void initCookie() throws URISyntaxException, IOException {
        stringListMap = Config.manager.get(new URI("https://item.jd.com/100010793473.html"), stringListMap);
        List<String> cookie = stringListMap.get("Cookie");
        stringListMap.clear();
        COOKIE = cookie;
        writer(cookie.get(0));
    }

    public static void writer(String cookie) throws IOException, URISyntaxException {
        OutputStream outputStream = new FileOutputStream("cookie.properties");
        byte[] data = cookie.getBytes();
        outputStream.write(data, 0, data.length);
        String time = "\n:" + System.currentTimeMillis();
        outputStream.write(time.getBytes());
        outputStream.close();
        log.info("写入Cookie");
    }


    public static String reader() {
        try {
            InputStream inputStream = new FileInputStream("cookie.properties");
            StringBuilder response = new StringBuilder();
            byte[] buffer;
            int length;
            buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) != -1) {
                response.append(new String(buffer, 0, length, "GBK"));
            }
            inputStream.close();
            String time = response.toString().split(":")[1];
            String cookie = response.toString().split(":")[0];
            if (System.currentTimeMillis() - Long.parseLong(time) > 24 * 60 * 60 * 1000) {
                return null;
            } else {
                log.info("读取Cookie");
                return cookie;
            }
        } catch (Exception e) {
            return null;
        }
    }
}
